<template>
  <div id="try">
    <!-- box_rolling下执行正面翻转动画   -->
    <div class="rollbox" :class="{'box_rolling':isRolling}" @click="rolling">
      <!-- 前面div -->
      <div class="rollbox_front">
        <div class="contentbox">
          <img src="@/assets/images/cardbg.png" />
        </div>
      </div>
      <!-- 后面div -->
      <div class="rollbox_behind">
        <div class="contentbox">
          <img :src="cardsrc" alt="picture" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'try',
    data() {
      return {
        isRolling: false,
        cardsrc: "",
        chooseid: 0
      }
    },
    created() {
      var count = this.$store.state.picnum
      var cardarray = []
      var probability = this.$store.state.probability
      for (let i = 0; i < count; i++) {
        cardarray.push(i + 1)
      }

      var index = this.random(cardarray, probability)
      while (index == 0) {
        index = Math.ceil(Math.random() * count)
      }
      console.log(index)
      this.chooseid = index
      this.cardsrc = require('../assets/images/card' +
        index + '.jpg')
    },
    methods: {
      random(arr1, arr2) {
        var sum = 0,
          factor = 0,
          random = Math.random();

        for (var i = arr2.length - 1; i >= 0; i--) {
          sum += arr2[i]; // 统计概率总和
        };
        random *= sum; // 生成概率随机数
        for (var i = arr2.length - 1; i >= 0; i--) {
          factor += arr2[i];
          if (random <= factor)
            return arr1[i];
        };
        return null;
      },
      rolling() {
        this.isRolling = !this.isRolling
        this.$emit('toResult', this.chooseid)
      }
    }
  }
</script>
<style lang='less'>
  #try {
    margin: 10px 0;

    .rollbox {
      position: relative;
      perspective: 1000px;

      &_front,
      &_behind {
        transform-style: preserve-3d; //表示所有子元素在3D空间中呈现
        backface-visibility: hidden; //元素背面向屏幕时是否可见
        transition-duration: .5s;
        transition-timing-function: 'ease-in';
        background: RGB(48, 72, 91);

        .contentbox {
          display: flex;
          justify-content: center;
          align-items: center;

          >img {
            width: 100%;
            height: 100%;
            box-shadow: 0 2px 4px rgba(0, 0, 0, .5), 0 0 6px rgba(0, 0, 0, .5);
          }
        }
      }

      &_behind {
        transform: rotateY(180deg);
        visibility: hidden; //元素不可见，但占据空间
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
      }
    }


    .box_rolling {
      .rollbox_front {
        transform: rotateY(180deg);
        visibility: hidden;
      }

      .rollbox_behind {
        transform: rotateY(360deg);
        visibility: visible;
      }
    }
  }
</style>